package com.geekjob1120.geekjob1120pay.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class SpringBeanUtil implements ApplicationContextAware {

    private static ClassPathXmlApplicationContext xmlApplicationContext;
    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        log.info("开始设置上下文对象:",applicationContext);
        SpringBeanUtil.context = applicationContext;
        SpringBeanUtil.xmlApplicationContext = new ClassPathXmlApplicationContext(applicationContext);
        SpringBeanUtil.xmlApplicationContext.setConfigLocation("beans.xml");
        SpringBeanUtil.xmlApplicationContext.refresh();
    }

    public static ApplicationContext getContext() {
        return context;
    }

    public static ClassPathXmlApplicationContext getXmlApplicationContext(){
        return xmlApplicationContext;
    }

    public static <T> T getBean(String beanName){
        if(context.containsBean(beanName)){
            log.info("通过普通context获取bean：{}",beanName);
            return (T) context.getBean(beanName);
        }else if(xmlApplicationContext.containsBean(beanName)){
            log.info("通过普通xmlcontext获取bean：{}",beanName);
            return (T)xmlApplicationContext.getBean(beanName);
        }else {
            log.info("未获取到bean定义：{}",beanName);
            return null;
        }
    }

}
